package com.edaoe.util;

import com.jfinal.kit.StrKit;
import com.jfinal.upload.UploadFile;

import java.io.*;

/**
 * Created by Dull on 2017/4/25 0025.
 */
public class FileUtil {

    public static String read(File file) {
        StringBuilder result = new StringBuilder();
        try {
            if (!file.exists())
                return "该文件不存在";
            BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
            String s;
            while ((s = br.readLine()) != null) {//使用readLine方法，一次读一行
                result.append(System.lineSeparator() + s);
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.toString();
    }

    public static void write(String filePath, String conent) {
        BufferedWriter out = null;
        try {
            File file=new File(filePath);
            if (!file.exists())
                createFile(filePath);
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
            out.newLine();
            out.newLine();
            out.write(conent);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void createFile(String filePath) {
        String rootPath=filePath.substring(0,filePath.lastIndexOf("/"));
        String fileName=filePath.substring(filePath.lastIndexOf("/")+1);
        File file = new File(rootPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        String courseListFile = rootPath + fileName;
        File txtFile = new File(courseListFile);
        if (!txtFile.exists()) {
            try {
                txtFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String renameToUUID(UploadFile uf) {
        String fileName= StrKit.getRandomUUID()+"."+getExtName(uf.getFileName());
        String newFilePath = uf.getUploadPath() + File.separator + fileName;
        uf.getFile().renameTo(new File(newFilePath));
        return fileName;
    }

    public static String getExtName(String fileName) {
        int index = fileName.lastIndexOf('.');
        if (index != -1 && (index + 1) < fileName.length()) {
            return fileName.substring(index + 1);
        } else {
            return null;
        }
    }
}
